package com.dup.jxlh.admin.controller;

import com.dup.jxlh.admin.entities.model.Role;
import com.dup.jxlh.admin.entities.vo.RoleVO;
import com.dup.jxlh.admin.service.RoleService;
import com.dup.jxlh.admin.validator.RoleId;
import com.dup.jxlh.api.entities.CommonResult;
import com.dup.jxlh.api.entities.PaginationData;
import com.dup.jxlh.api.enums.ResultEnum;
import com.dup.jxlh.api.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;

@RestController
@RequestMapping("/role")
@Validated
public class RoleController {
    @Autowired
    private RoleService roleService;

    @PostMapping("/getRoleList")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Show')")
    public CommonResult getRoleList(PaginationData paginationData) {
        return ResultUtil.result(ResultEnum.SUCCESS, roleService.getRoleList(paginationData));
    }

    @PostMapping("/addRole")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Operate')")
    public CommonResult addRole(@Validated Role role) {
        if (roleService.addRole(role)) {
            return ResultUtil.result(ResultEnum.SUCCESS);
        }
        return ResultUtil.result(ResultEnum.ERROR);
    }

    @PostMapping("/editRole")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Operate')")
    public CommonResult editRole(@Validated Role role) {
        role.setCompanyId(null);
        if (roleService.editRole(role)) {
            return ResultUtil.result(ResultEnum.SUCCESS);
        }
        return ResultUtil.result(ResultEnum.ERROR);
    }

    @PostMapping("/getMainPerm")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Show')")
    public CommonResult getMainPerm() {
        return ResultUtil.result(ResultEnum.SUCCESS, roleService.getMainPerm());
    }

    @PostMapping("/getRolePermIds")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Show')")
    public CommonResult getRolePermIds(@RequestParam("roleId") @RoleId BigInteger roleId) {
        return ResultUtil.result(ResultEnum.SUCCESS, roleService.getRolePermIds(roleId));
    }

    @PostMapping("/updateRolePerm")
    @PreAuthorize("hasAnyAuthority('ROLE_Admin','ROLE_UserPerm_Operate')")
    public CommonResult updateRolePerm(@Validated RoleVO roleVO) {
        if (roleService.updateRolePerm(roleVO)) {
            return ResultUtil.result(ResultEnum.SUCCESS);
        }
        return ResultUtil.result(ResultEnum.ERROR);
    }
}
